<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ring extends MY_Controller{

	function __construct(){
		parent::__construct();
	}

	public function index(){
		// echo base_url();exit();
		$userId = $this->get_user_id();
		$userName = $this->UsersModel->get_name_by_id($userId);
		$uploadError = $this->session->flashdata('error');
		$uploadInfo = $this->session->flashdata('upload_data');
		$alert = "";

		if($uploadInfo){
			// $alert = 'alert(\''.$uploadInfo['file_name'].' 上传成功\');';
			$alert = '';
		}

		if($uploadError){
			$alert = 'alert("'.$uploadError.'");';
		}
		//获得资源的内容
		// $resources = $this->ResourcesModel->get_resources_by_name($userName);
		
		//获得资源条数
		$resourcesNum = $this->ResourcesModel->get_resource_num($userName);

		//分页配置
		$config['base_url'] = 'http://localhost/EECloud/index.php/ring/index';
		$config['total_rows'] = $this->db->get('resources')->num_rows();
		$config['per_page'] = 15;
		$config['num_links'] = 20;
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$this->pagination->initialize($config);
		$this->db->where('flag','0');
		$records = $this->db->get('resources',$config['per_page'],$this->uri->segment(3))->result_array();
		$data = array(
			// 'userId' => $userId,
			'records' => $records,
			'userName' => $userName,
			'alert' => $alert,
			// 'resources' => $resources,
			'resourcesNum' => $resourcesNum,
			'menuTitle' => 'allMenu'
		);

		$this->load->view('ringCloud/header',$data);
		$this->load->view('ringCloud/footer');
	}

	public function files(){
		$userId = $this->get_user_id();
		$userName = $this->UsersModel->get_name_by_id($userId);
		// $resources = $this->ResourcesModel->get_resource_by_type($userName,'text');
		$resourcesNum = $this->ResourcesModel->get_resource_num_by_type($userName,'text');
		$alert = "";
		
		//分页配置
		$config['base_url'] = 'http://localhost/EECloud/index.php/ring/files';
		$this->db->where('resourceType','text');
		$config['total_rows'] = $this->db->get('resources')->num_rows();
		$config['per_page'] = 15;
		$config['num_links'] = 20;
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$this->pagination->initialize($config);
		$this->db->where('resourceType','text');
		$this->db->where('flag','0');
		$records = $this->db->get('resources',$config['per_page'],$this->uri->segment(3))->result_array();

		$data = array(
			'records' => $records,
			'userName' => $userName,
			'alert' => $alert,
			'menuTitle' => 'filesMenu',
			// 'resources' => $resources,
			'resourcesNum' => $resourcesNum
		);
		$this->load->view('ringCloud/header',$data);
		$this->load->view('ringCloud/footer');
	}

	public function images(){
		$userId = $this->get_user_id();
		$userName = $this->UsersModel->get_name_by_id($userId);
		// $resources = $this->ResourcesModel->get_resource_by_type($userName,'image');
		$resourcesNum = $this->ResourcesModel->get_resource_num_by_type($userName,'image');
		$alert = "";
		//分页配置
		$config['base_url'] = 'http://localhost/EECloud/index.php/ring/images';
		$this->db->where('resourceType','image');
		$config['total_rows'] = $this->db->get('resources')->num_rows();
		$config['per_page'] = 15;
		$config['num_links'] = 20;
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$this->pagination->initialize($config);
		$this->db->where('resourceType','image');
		$this->db->where('flag','0');
		$records = $this->db->get('resources',$config['per_page'],$this->uri->segment(3))->result_array();

		$data = array(
			'records' => $records,
			'userName' => $userName,
			'alert' => $alert,
			// 'resources' => $resources,
			'resourcesNum' => $resourcesNum,
			'menuTitle' => 'imagesMenu'
		);
		$this->load->view('ringCloud/header',$data);
		$this->load->view('ringCloud/footer');
	}

	public function vedios(){
		$userId = $this->get_user_id();
		$userName = $this->UsersModel->get_name_by_id($userId);
		// $resources = $this->ResourcesModel->get_resource_by_type($userName,'vedio');
		$resourcesNum = $this->ResourcesModel->get_resource_num_by_type($userName,'vedio');
		$alert = "";

		//分页配置
		$config['base_url'] = 'http://localhost/EECloud/index.php/ring/vedios';
		$this->db->where('resourceType','vedio');
		$config['total_rows'] = $this->db->get('resources')->num_rows();
		$config['per_page'] = 15;
		$config['num_links'] = 20;
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$this->pagination->initialize($config);
		$this->db->where('resourceType','vedio');
		$this->db->where('flag','0');
		$records = $this->db->get('resources',$config['per_page'],$this->uri->segment(3))->result_array();

		$data = array(
			'records' => $records,
			'userName' => $userName,
			'alert' => $alert,
			// 'resources' => $resources,
			'resourcesNum' => $resourcesNum,
			'menuTitle' => 'vediosMenu'
		);
		$this->load->view('ringCloud/header',$data);
		$this->load->view('ringCloud/footer');
	}

	public function music(){
		$userId = $this->get_user_id();
		$userName = $this->UsersModel->get_name_by_id($userId);
		// $resources = $this->ResourcesModel->get_resource_by_type($userName,'audio');
		$resourcesNum = $this->ResourcesModel->get_resource_num_by_type($userName,'audio');
		$alert = "";

		//分页配置
		$config['base_url'] = 'http://localhost/EECloud/index.php/ring/music';
		$this->db->where('resourceType','audio');
		$config['total_rows'] = $this->db->get('resources')->num_rows();
		$config['per_page'] = 15;
		$config['num_links'] = 20;
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$this->pagination->initialize($config);
		$this->db->where('resourceType','audio');
		$this->db->where('flag','0');
		$records = $this->db->get('resources',$config['per_page'],$this->uri->segment(3))->result_array();

		$data = array(
			'records' => $records,
			'userName' => $userName,
			'alert' => $alert,
			// 'resources' => $resources,
			'resourcesNum' => $resourcesNum,
			'menuTitle' => 'musicMenu'
		);
		$this->load->view('ringCloud/header',$data);
		$this->load->view('ringCloud/footer');
	}

	public function others(){
		$userId = $this->get_user_id();
		$userName = $this->UsersModel->get_name_by_id($userId);
		// $resources = $this->ResourcesModel->get_resource_by_type($userName,'others');
		$resourcesNum = $this->ResourcesModel->get_resource_num_by_type($userName,'others');
		$alert = "";

		//分页配置
		$config['base_url'] = 'http://localhost/EECloud/index.php/ring/others';
		$this->db->where('resourceType','others');
		$config['total_rows'] = $this->db->get('resources')->num_rows();
		$config['per_page'] = 15;
		$config['num_links'] = 20;
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$this->pagination->initialize($config);
		$this->db->where('resourceType','others');
		$this->db->where('flag','0');
		$records = $this->db->get('resources',$config['per_page'],$this->uri->segment(3))->result_array();

		$data = array(
			'records' => $records,
			'userName' => $userName,
			'alert' => $alert,
			// 'resources' => $resources,
			'resourcesNum' => $resourcesNum,
			'menuTitle' => 'othersMenu'
		);
		$this->load->view('ringCloud/header',$data);
		$this->load->view('ringCloud/footer');
	}

	public function shares(){
		$userId = $this->get_user_id();
		$userName = $this->UsersModel->get_name_by_id($userId);
		// $resources = array();
		// $resource = $this->ResourceDescModel->get_all_share($userId);
		$resourcesNum = $this->ResourceDescModel->get_resource_num($userId);

		//分页配置
		$config['base_url'] = 'http://localhost/EECloud/index.php/ring/index';
		$config['total_rows'] = $this->db->get('resources')->num_rows();
		$config['per_page'] = 15;
		$config['num_links'] = 20;
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$this->pagination->initialize($config);
		$this->db->where('type','2');
		$records = $this->db->get('resource_desc',$config['per_page'],$this->uri->segment(3))->result_array();
		// var_dump($records);exit();
		$data = array(
			'records' => $records,
			'userName' => $userName,
			'menuTitle' => 'sharesMenu',
			// 'resources' => $resource,
			'resourcesNum' => $resourcesNum
		);
		$this->load->view('ringCloud/shares',$data);
	}

	public function recycleBin(){
		$userId = $this->get_user_id();
		$userName = $this->UsersModel->get_name_by_id($userId);
		//获取回收站的资源
		// $resources = $this->ResourcesModel->get_recycle_resource($userName);
		//获取回收站资源的数目
		$resourcesNum = $this->ResourcesModel->get_recycle_resource_num($userName);

		//分页配置
		$config['base_url'] = 'http://localhost/EECloud/index.php/ringCloud/recycleBin';
		$config['total_rows'] = $this->db->get('recycle')->num_rows();
		$config['per_page'] = 15;
		$config['num_links'] = 20;
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$this->pagination->initialize($config);
		$this->db->where('userName',$userName);
		$this->db->where('flag','1');
		$records = $this->db->get('resources',$config['per_page'],$this->uri->segment(3))->result_array();


		$data = array(
			'records' => $records,
			'userName' => $userName,
			'menuTitle' => 'recycleMenu',
			// 'resources' => $resources,
			'resourcesNum' => $resourcesNum
		);
		$this->load->view('ringCloud/recycleBin',$data);
	}

	public function do_upload(){
		
		$userName = $_POST['userName'];
		$fileName = $_FILES['userfile']['name'];
		$fileSize = round($_FILES['userfile']['size']/1024,2);
		// $fileType = $_FILES['userfile']['type'];
		$fileArr = explode('.', $fileName);
		$fileExt = array_pop($fileArr);
		$fileExt = trim($fileExt);
		$fileType = trim($fileExt);

		if($fileType == 'jpg'||$fileType == 'jpeg'||$fileType == 'bmp'||$fileType == 'gif'||$fileType == 'png'||$fileType == 'jpe'||$fileType == 'tiff'||$fileType == 'tif'){
			$fileType = 'image';
		}else if($fileType == 'mid'||$fileType == 'midi'||$fileType == 'mpga'||$fileType == 'mp3'||$fileType == 'wav'||$fileType == 'aif'||$fileType == 'aiff'||$fileType == 'aifc'||$fileType == 'ram'||$fileType == 'rm'||$fileType == 'rpm'||$fileType == 'ra'){
			$fileType = 'audio';
		}else if($fileType == 'movie'||$fileType == 'avi'||$fileType == 'mov'||$fileType == 'qt'||$fileType == 'mpe'||$fileType == 'mpeg'||$fileType == 'rv'||$fileType == 'flv'){
			$fileType = 'vedio';
		}else if($fileType == 'txt'||$fileType == 'text'||$fileType == 'log'||$fileType == 'rtx'||$fileType == 'rtf'||$fileType == 'doc'||$fileType == 'docx'||$fileType == 'ppt'||$fileType == 'pptx'||$fileType == 'xls'||$fileType == 'xlsx'||$fileType == 'pdf'){
			$fileType = 'text';
		}else{
			$fileType = 'others';
		}

		$info = array(
			'resourcePath' => './uploads/'.$userName.'/'.$fileName,
			'resourceName' => $fileName,
			'size' => $fileSize,
			'uploadTime' => date('Y-m-d H:i:s'),
			'userName' => $userName,
			'resourceType' => $fileType,
			'flag' => 0
		);
		$userId = $this->get_user_id();
		$userName = $this->UsersModel->get_name_by_id($userId);
		$config['upload_path'] = './uploads/'.$userName.'/';
		// $config['allowed_types'] = 'gif|png|jpg|txt|ppt|pptx|doc|docx|xlsx|html|mp3';
		$config['allowed_types'] = "*";
		$config['max_size'] = '0';
		$config['max_width']  = '1024';
		$config['max_height']  = '768';
		$config['remove_spaces'] = FALSE;
		$config['overwrite'] = TRUE;
		$this->load->library('upload',$config);
		// $this->upload->do_upload();
		if(!$this->upload->do_upload()){
			$error = array('error' => $this->upload->display_errors('', ''));
	        $this->session->set_flashdata($error);
	        redirect('ring');
		}else{
			// $this->add_resource_info($info);
			$this->ResourcesModel->add_resource($info);
  			$data = array('upload_data' => $this->upload->data());
	      	$this->session->set_flashdata($data);
	     	redirect('ring');
		}
	}

	public function do_download(){
		$this->load->helper('download');
		$resourceId = $_GET['rId'];
		$resourcePath = $this->ResourcesModel->get_resource_path($resourceId);
		$resourceName = $this->ResourcesModel->get_resource_name($resourceId);
		$file_path = $resourcePath['resourcePath'];
	
		header("Content-type:text/html;charset=utf-8"); 
		$file_name=$resourceName['resourceName']; 
		//用以解决中文不能显示出来的问题 
		$file_name = iconv("utf-8","gb2312",$file_name);
		$file_path = iconv("utf-8","gb2312",$file_path); 
		// $file_path = '../../20130911112438.zip';
		//首先要判断给定的文件存在与否 
		if(!file_exists($file_path)){ 
			echo "没有该文件文件"; 
			return ; 
		} 
		$fp=fopen($file_path,"r"); 
		$file_size=filesize($file_path); 
		//下载文件需要用到的头 
		Header("Content-type: application/octet-stream"); 
		Header("Accept-Ranges: bytes"); 
		Header("Accept-Length:".$file_size); 
		Header("Content-Disposition: attachment; filename=".$file_name); 
		$buffer=1024; 
		$file_count=0; 
		//向浏览器返回数据 
		while(!feof($fp) && $file_count<$file_size){ 
			$file_con=fread($fp,$buffer); 
			$file_count+=$buffer; 
			echo $file_con; 
		} 
		fclose($fp);

	}

	//把资源放入回收站
	public function drop_recycle(){
		$resourceId = $_GET['rId'];
		$flag = '1';
		$deleteTime = date('Y-m-d H:i:s');
		$this->ResourcesModel->alter_resource($resourceId,$flag,$deleteTime);
		// echo $resourceId;exit();
		redirect('ring');
	}

	//把回收站的资源还原
	public function undo_resource(){
		$resourceId = $_GET['rId'];
		$flag = '0';
		$deleteTime = '';
		$this->ResourcesModel->undo_resource($resourceId,$flag,$deleteTime);
		redirect('ring');
	}

	//把所选资源放入回收站
	public function drop_all_recycle(){
		$resourceId = $_GET['resourceId'];
		$allId = explode(',', $resourceId);
		for($i = 0; $i < count($allId); $i++){
			$flag = '1';
			$deleteTime = date('Y-m-d H:i:s');
			$this->ResourcesModel->alter_resource($allId[$i],$flag,$deleteTime);
		}
		redirect('ring');
	}

	//删除单个资源
	public function delete_resource(){
		$resourceId = $_GET['rId'];
		$resourcePath = $this->ResourcesModel->get_recycle_path($resourceId);
		// var_dump($resourceId);exit();
		//判断回收站是否存在多个相同文件，如果存在不删除文件，否则删除文件
		if($this->ResourcesModel->check_recycle_path($resourcePath['resourcePath'])){
			$file_path = iconv("utf-8","gb2312",$resourcePath['resourcePath']);
			unlink($file_path);
			$this->ResourcesModel->delete_resource($resourceId);
		}else{
			$this->ResourcesModel->delete_resource($resourceId);
		}
		
		redirect('ring/recycleBin');
	}

	//删除所选资源
	public function delete_all_resource(){
		$userName = $_GET['userName'];
		$resourcePath = $this->ResourcesModel->get_recycle_resource_path($userName);
		// var_dump($resourcePath['0']);exit();
		for($i = 0;$i < count($resourcePath);$i++){
			if($this->ResourcesModel->check_recycle_path($resourcePath[$i]['resourcePath'])){
				$file_path = iconv("utf-8","gb2312",$resourcePath[$i]['resourcePath']);
				unlink($file_path);
				$this->ResourcesModel->delete_resource_by_path($resourcePath[$i]['resourcePath']);
			}else{
				$this->ResourcesModel->delete_resource_by_path($resourcePath[$i]['resourcePath']);
			}
		}
		// $this->ResourcesModel->delete_resource_by_username($userName);
		redirect('ring/recycleBin');
	}
	
	//对需要下载的文件进行打包下载
	public function tozip(){
		$resourceId = $_GET['resourceId'];
		$allId = explode(',', $resourceId);
		$zip = new ZipArchive();
		$zipname = date('YmdHis',time());
		// echo $zipname;
		if (!file_exists($zipname)){ 
			// echo $zipname;
			$zip->open($zipname.'.zip',ZipArchive::OVERWRITE);//创建一个空的zip文件 
			for ($i=0;$i<count($allId);$i++){ 
				$resourcePath = $this->ResourcesModel->get_resource_path($allId[$i]);
				$resourceName = $this->ResourcesModel->get_resource_name($allId[$i]);
				$file_name = iconv("utf-8","gb2312",$resourceName['resourceName']);
				$file_path = iconv("utf-8","gb2312",$resourcePath['resourcePath']); 
				$zip->addFile($file_path,$file_name); 
			}
			$zip->close();
			$path = './'.$zipname.'.zip';
			$this->download_by_path($path,$zipname.'.zip');
			//删除打包文件
			unlink($path);
		}

	}

	//根据路径下载文件
	public function download_by_path($path,$name){

		header("Content-type:text/html;charset=utf-8");  
		// $file_name = 'myphote.zip';
		// $file_path = "./20130909145440.zip";
		$file_path = $path;
		$file_name = $name;
		//用以解决中文不能显示出来的问题 
		$file_name = iconv("utf-8","gb2312",$file_name);
		$file_path = iconv("utf-8","gb2312",$file_path); 
		// $file_path = '../../20130911112438.zip';
		//首先要判断给定的文件存在与否 
		if(!file_exists($file_path)){ 
			echo "没有该文件文件"; 
			return ; 
		} 
		$fp=fopen($file_path,"r"); 
		$file_size=filesize($file_path); 
		//下载文件需要用到的头 
		Header("Content-type: application/octet-stream"); 
		Header("Accept-Ranges: bytes"); 
		Header("Accept-Length:".$file_size); 
		Header("Content-Disposition: attachment; filename=".$file_name); 
		$buffer=1024; 
		$file_count=0; 
		//向浏览器返回数据 
		while(!feof($fp) && $file_count<$file_size){ 
			$file_con=fread($fp,$buffer); 
			$file_count+=$buffer; 
			echo $file_con; 
		} 
		fclose($fp);

	}

	//还原资源时判断该资源是否已存在
	public function ajax_check_resource(){
		$resourceId = $this->input->get_post('rId');
		$resourcePath = $this->ResourcesModel->get_recycle_path($resourceId);
		// var_dump($resourcePath['resourcePath']);
		//根据flag=0和resourcePath查找是否存在该资源
		$result = $this->ResourcesModel->is_resource_exist($resourcePath['resourcePath']);
		$json = array('success' => $result);
		echo json_encode($json);
		exit(0);
	}

	public function search_index(){
		$userName = $this->input->get_post('userName');
		$key = $this->input->get_post('key');
		$resources = $this->ResourcesModel->get_search_resources($userName,$key);
		// var_dump(gettype($resources));exit();
		// $resources = $this->input->get_post('resources');
		$resourcesNum = count($resources);
		$userId = $this->get_user_id();
		$userName = $this->UsersModel->get_name_by_id($userId);
		$uploadError = $this->session->flashdata('error');
		$uploadInfo = $this->session->flashdata('upload_data');
		$alert = "";
		if($uploadInfo){
			// $alert = 'alert(\''.$uploadInfo['file_name'].' 上传成功\');';
			$alert = '';
		}

		if($uploadError){
			$alert = 'alert("'.$uploadError.'");';
		}

		$data = array(
			// 'userId' => $userId,
			'userName' => $userName,
			'alert' => $alert,
			'records' => $resources,
			'resourcesNum' => $resourcesNum,
			'menuTitle' => 'allMenu'
		);

		$this->load->view('ringCloud/header',$data);
		$this->load->view('ringCloud/footer');
	}

	public function remove_share(){
		//获取需要删除共享的资源Id
		$id = $this->input->get_post('id');
		//根据资源id从resourcedesc表中删除资源
		$resulet = $this->ResourceDescModel->remove_share($id);
		redirect('ring/shares');
	}
}